<?php

namespace app\admin\service;

use app\admin\dao\MemberDraftDao;
use app\admin\dao\MemberInfoDao;
use app\admin\model\UM as UM;
use app\common\model\Area;
use app\common\model\CustomPush;
use app\common\model\MemberDraft;
use app\common\model\MemberInfo;
use app\common\service\TemplateSmsService;
use app\index\service\CustomPushService;
use app\index\service\MemberTokenService;
use ShidianUtil\Exception\DataNotExistException;
use ShidianUtil\Utils\ArrayUtil;
use ShidianUtil\Utils\CheckUtil;
use think\exception\ValidateException;

/**
 * Class LawyerDraftCheckService
 * @package app\member\service
 */
class LawyerDraftCheckService
{
    private MemberDraftDao $memberDraftDao;

    public function __construct(MemberDraftDao $memberDraftDao)
    {
        $this->memberDraftDao = $memberDraftDao;
    }

    /**
     * 更新
     * @param \app\admin\model\UM $user
     * @param int $id
     * @param array $params
     * @return \app\common\model\MemberDraft
     */
    public function modify(UM $user, int $id, array $params): MemberDraft
    {
        $params['checkStatus'] ??= null;
        $params['checkStatus'] = $params['checkStatus'] == 1 ? 1 : 2;
        $params['practiceTime'] ??= time();
        $params['checkCause'] ??= '';

        $record = MemberDraft::field(true)
            ->with([
                'member',
                'categories',
            ])
            ->where('id', $id)
            ->find();

        if (is_null($record)) {
            throw new DataNotExistException('该申请不存在或已被删除');
        }

        $member = $record->member;

        // 拒绝需要理由
        if ($params['checkStatus'] == 2 && is_blank($params['checkCause'] ?? null)) {
            throw new ValidateException('请输入拒绝理由');
        }

        if ($record->checkStatus == $params['checkStatus']) {
            throw new ValidateException('请勿重复操作');
        }

        $record->checkStatus = $params['checkStatus'];
        $record->practiceTime = $params['practiceTime'];
        $record->checkCause = $params['checkCause'];
        $record->save();

        if ($params['checkStatus'] == 1) {
            // 通过

            // 写入 律师信息
            $this->saveMemberInfo($record);

            // 更新用户信息
            $member->realname = $record->realname ?? '';
            $member->checkStatus = $record->checkStatus;
            $member->headImgUrl = $record->headImgUrl;
            $member->type = '1';
            $member->subType = $record->subType;
            $member->isSettled = '2';
            $member->settledTime = time();

            if (not_blank($record->cropImgUrl)) {
                $member->cropImgUrl = $record->cropImgUrl;
            }

            $member->save();

            // 写入定制推送
            $this->saveCustomPush($member->id, $record->cityId);

            // TODO 记录日志 律师认证通过
            $result = '已通过';

            // 审核通过后，让用户退出登录
            $this->getMemberTokenService()->delete($member->id);

            // 审核后，触发邀请事件
            event('MemberInvited', ['memberIdInvite' => $record->id]);

        } else {
            // 拒绝

            $member->isSettled = '0';
            $member->save();

            // TODO 记录日志 律师认证未通过
            $result = '未通过';
        }

        //审核后，给律师发短信说审核完成
        $phone = $member->phone;
        if (CheckUtil::isPhoneNumber($phone)) {

            if ($record->subType == 0) {
                // 律师
                $this->getTemplateSmsService()->lawyerCheckResult($phone, $result);
            } elseif ($record->subType == 1) {
                // 法务
                $this->getTemplateSmsService()->legalCheckResult($phone, $result);
            }

        }

        return $record;
    }

    /**
     * 写入 律师信息
     * @param MemberDraft $draft
     * @return void
     */
    private function saveMemberInfo(MemberDraft $draft)
    {
        $keys = [
            'memberId', 'realname', 'provinceId', 'cityId', 'practiceNumber', 'practicingLawFirm', 'certificatePic',
            'practiceTime', 'introduce', 'lawFirmAdd', 'chargingStandard', 'checkTime', 'idcardPic', 'idcard2Pic', 'idcard', 'legalCompany'
        ];

        $params = ArrayUtil::cut($draft->toArray(), $keys);

        // 默认评分4.9
        $params['commentLevel'] = 4.9;
        $params['checkTime'] = time();

        $result = $this->getMemberInfoDao()->insertActiveDuplicate($params, $keys, $keys);

        $memberInfo = MemberInfo::where('memberId', $result->memberId)->find();

        if ($memberInfo && !$draft->categories->isEmpty()) {
            $memberInfo->categories()->sync($draft->categories->column('id'));
        }
    }

    // 写入定制推送
    public function saveCustomPush($memberId, $cityId)
    {
        $record = CustomPush::where('memberId', $memberId)->find();

        // 插入记录
        if ($record) {
            return;
        }

        $pushStatus = 1;

        $cityArr = [];
        $city = Area::where('id', $cityId)->find();
        if ($city) {
            $cityArr[] = $city;
        }

        $sourceType = [
            'name' => '全部',
        ];
        $sourceTypeArr = [];
        $sourceTypeArr[] = $sourceType;

        $kwsPushStatus = 0;
        $kwsStr = '';

        $this->getCustomPushService()->replaceCustomPush($memberId, $pushStatus, $cityArr, $sourceTypeArr, $kwsPushStatus, $kwsStr);
    }

    private function getMemberInfoDao(): MemberInfoDao
    {
        return app(MemberInfoDao::class);
    }

    private function getTemplateSmsService(): TemplateSmsService
    {
        return app(TemplateSmsService::class);
    }

    private function getMemberTokenService(): MemberTokenService
    {
        return app(MemberTokenService::class);
    }

    private function getCustomPushService(): CustomPushService
    {
        return app(CustomPushService::class);
    }
}
